// 安全的全局反馈工具
export interface ToastOptions {
  duration?: number;
  type?: 'info' | 'success' | 'warning' | 'error';
}

export interface ConfirmOptions {
  title?: string;
  message: string;
  confirmText?: string;
  cancelText?: string;
}

let toastCount = 0;

export function toast(message: string, options: ToastOptions = {}): void {
  if (!message?.trim()) return;
  
  const { duration = 3000, type = 'info' } = options;
  const id = `gce-toast-${++toastCount}`;
  
  // 创建toast元素
  const toast = document.createElement('div');
  toast.id = id;
  toast.className = `gce-toast gce-toast-${type}`;
  toast.textContent = message;
  
  // 应用样式
  Object.assign(toast.style, {
    position: 'fixed',
    top: '16px',
    left: '50%',
    transform: 'translateX(-50%)',
    background: type === 'error' ? '#ef4444' : type === 'warning' ? '#f59e0b' : type === 'success' ? '#10b981' : 'rgba(0,0,0,.75)',
    color: '#fff',
    padding: '10px 14px',
    borderRadius: '10px',
    fontSize: '14px',
    boxShadow: '0 10px 24px rgba(0,0,0,.35)',
    zIndex: '400000',
    pointerEvents: 'auto',
    maxWidth: '80vw',
    wordBreak: 'break-word'
  });
  
  document.body.appendChild(toast);
  
  // 自动移除
  setTimeout(() => {
    try {
      if (toast.parentNode) {
        toast.parentNode.removeChild(toast);
      }
    } catch {}
  }, duration);
}

export function confirm(options: ConfirmOptions | string): Promise<boolean> {
  const opts = typeof options === 'string' ? { message: options } : options;
  const {
    title = '确认',
    message,
    confirmText = '确定',
    cancelText = '取消'
  } = opts;
  
  if (!message?.trim()) {
    return Promise.resolve(false);
  }
  
  return new Promise((resolve) => {
    const id = `gce-confirm-${Date.now()}`;
    
    // 创建遮罩
    const mask = document.createElement('div');
    mask.id = `${id}-mask`;
    Object.assign(mask.style, {
      position: 'fixed',
      inset: '0',
      background: 'rgba(0,0,0,.35)',
      backdropFilter: 'blur(6px)',
      zIndex: '300010'
    });
    
    // 创建对话框
    const modal = document.createElement('div');
    modal.id = id;
    Object.assign(modal.style, {
      position: 'fixed',
      left: '50%',
      top: '50%',
      transform: 'translate(-50%, -50%)',
      minWidth: '280px',
      maxWidth: '80vw',
      background: 'var(--card, #fff)',
      color: 'var(--text, #000)',
      border: '1px solid var(--border, #e5e7eb)',
      borderRadius: '14px',
      padding: '16px',
      boxShadow: '0 18px 48px rgba(0,0,0,.45)',
      zIndex: '300020'
    });
    
    // 内容
    const content = document.createElement('div');
    if (title) {
      const titleEl = document.createElement('div');
      titleEl.textContent = title;
      titleEl.style.fontWeight = 'bold';
      titleEl.style.marginBottom = '8px';
      content.appendChild(titleEl);
    }
    
    const messageEl = document.createElement('div');
    messageEl.textContent = message;
    messageEl.style.lineHeight = '1.6';
    messageEl.style.marginBottom = '12px';
    content.appendChild(messageEl);
    
    // 按钮
    const actions = document.createElement('div');
    Object.assign(actions.style, {
      display: 'flex',
      justifyContent: 'flex-end',
      gap: '10px'
    });
    
    const cancelBtn = document.createElement('button');
    cancelBtn.textContent = cancelText;
    Object.assign(cancelBtn.style, {
      padding: '8px 12px',
      borderRadius: '10px',
      cursor: 'pointer',
      border: '1px solid var(--border, #e5e7eb)',
      background: 'var(--card, #fff)',
      color: 'var(--text, #000)'
    });
    
    const confirmBtn = document.createElement('button');
    confirmBtn.textContent = confirmText;
    Object.assign(confirmBtn.style, {
      padding: '8px 12px',
      borderRadius: '10px',
      cursor: 'pointer',
      border: 'none',
      background: 'var(--primary, #3b82f6)',
      color: '#fff'
    });
    
    actions.appendChild(confirmBtn);
    actions.appendChild(cancelBtn);
    
    content.appendChild(actions);
    modal.appendChild(content);
    
    // 清理函数
    const cleanup = () => {
      try {
        if (mask.parentNode) mask.parentNode.removeChild(mask);
        if (modal.parentNode) modal.parentNode.removeChild(modal);
      } catch {}
    };
    
    // 事件监听
    const handleCancel = () => {
      cleanup();
      resolve(false);
    };
    
    const handleConfirm = () => {
      cleanup();
      resolve(true);
    };
    
    cancelBtn.addEventListener('click', handleCancel);
    confirmBtn.addEventListener('click', handleConfirm);
    mask.addEventListener('click', handleCancel);
    
    // ESC键支持
    const handleKeydown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        document.removeEventListener('keydown', handleKeydown);
        handleCancel();
      }
    };
    document.addEventListener('keydown', handleKeydown);
    
    // 添加到DOM
    document.body.appendChild(mask);
    document.body.appendChild(modal);
    
    // 聚焦确认按钮
    confirmBtn.focus();
  });
}